package com.recharge;

import com.alibaba.fastjson.JSON;
import com.recharge.callback.AbsCallBackService;
import com.recharge.domain.*;
import com.recharge.mapper.*;
import com.recharge.sup.AbsSupChargeService;
import com.recharge.utils.OrderStatus;
import com.recharge.utils.ProcessResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * Created by CAOQI on 2017/1/7.
 */
@Service
public class AsyncTaskService {

    @Resource(name = "channelMap")
    private Map<String,AbsSupChargeService> channelMap;

    @Autowired
    private OrderService orderService;

    @Autowired
    private TradeNotifyMapper tradeNotifyMapper;

    @Autowired
    private ITradeOrderMapper iTradeOrderMapper;

    @Autowired
    private ITradeMerchantMapper itradeMerchantMapper;

    @Autowired
    private ISalePriceMapper iSalePriceMapper;


    @Autowired
    private IProductMapper iProductMapper;

    @Resource(name = "callBackMap")
    private Map<String,AbsCallBackService> callMap;


    private Logger logger = LoggerFactory.getLogger(getClass());

    @Async(value = "queryOrderToChannel")
    public void query(TradeOrder tradeOrder,TradeFlow tradeFlow){
        String supUid = tradeOrder.getSupId();
        if (StringUtils.isEmpty(tradeOrder.getSupId())){
            if (StringUtils.equals(tradeFlow.getChannelId()+"","5882")){
                supUid="yunll";
            }else if(StringUtils.equals(tradeFlow.getChannelId()+"","6044")){
                supUid="yunll2";
            }
        }
        ProcessResult processResult = channelMap.get(supUid).query(tradeOrder, tradeFlow);

        if(StringUtils.equals(processResult.getCode(), ProcessResult.SUCCESS)){
            logger.info("order success.order id{}",tradeOrder.getOrderId());
            orderService.SUCCESS(tradeOrder, tradeFlow);
        }else if(StringUtils.equals(processResult.getCode(),ProcessResult.FAIL)){
            orderService.FAIL(tradeOrder, tradeFlow);
            logger.info("order fail.order id{}",tradeOrder.getOrderId());
        }else if(StringUtils.equals(processResult.getCode(),ProcessResult.PROCESSING)){
            logger.info("order processing。.order id{}",tradeOrder.getOrderId());
        }else{
            logger.info("order unkown.no process . order id{}", tradeOrder.getOrderId());
        }
    }

    @Async(value = "sendOrderToChannel")
    public void recharge(TradeOrder tradeOrder,TradeFlow tradeFlow){
        ProcessResult processResult = channelMap.get(tradeOrder.getSupId()).recharge(tradeOrder,tradeFlow);

        if(StringUtils.equals(processResult.getCode(), ProcessResult.SUCCESS)){
            logger.info("submit order success.order id{}",tradeOrder.getOrderId());
        }else if(StringUtils.equals(processResult.getCode(),ProcessResult.FAIL)){
            orderService.RECHARGE_FAIL(tradeOrder, tradeFlow);
            logger.info("submit order fail.order id{}",tradeOrder.getOrderId());
        }else{
            logger.info("submit order unkown.order id{}",tradeOrder.getOrderId());
            orderService.UNKNOWN(tradeOrder, tradeFlow);
        }
    }

    @Async(value = "callBack")
    public void callBack(TradeNotify tradeNotify ,TradeOrder tradeOrder,TradeMerchant tradeMerchant,String callType){

        ProcessResult processResult = callMap.get(callType).callBack(tradeOrder,tradeMerchant);

        if (StringUtils.equals(processResult.getCode(),ProcessResult.SUCCESS)){
            tradeNotifyMapper.updateStatus("0",tradeNotify.getOrderId());
                tradeOrder.setTmStatus((short) 0);
            iTradeOrderMapper.updateTmState(tradeOrder);
        }else if(StringUtils.equals(processResult.getCode(),ProcessResult.FAIL)){
            tradeNotifyMapper.updateStatus("0",tradeNotify.getOrderId());
            tradeNotifyMapper.updateCount(tradeNotify.getOrderId());
            tradeOrder.setTmStatus((short) 3);
            iTradeOrderMapper.updateTmState(tradeOrder);


            //                如果商户的类型不是1 则需要扣款。1的则是店铺类型的
            if (!StringUtils.equals(tradeMerchant.getType(),"1") && tradeOrder.getOrderCost()!=null){

                Product product = new Product() ;
                product.setProductName(tradeOrder.getProduct());
                product = iProductMapper.selectOne(product);
                SalePrice salePrice = iSalePriceMapper.selectByMidPid(tradeOrder.getMerId(), product.getProductId());

                if (salePrice==null){
                    salePrice = iSalePriceMapper.selectByMidPid("default", product.getProductId());
                }

//
                if (itradeMerchantMapper.addBalance(tradeOrder.getMerId(), salePrice.getSalePrice())!=1){
                    logger.info("orderId: {} ,add balance fail.",tradeOrder.getOrderId());
                }
            }
        }else{
            tradeNotifyMapper.updateCount(tradeNotify.getOrderId());
        }
    }
}
